<template>
  <div>
    <el-form inline :model="itemRequestQuery" ref="queryFormRef">
      <el-form-item prop="keywords">
        <el-input v-model="itemRequestQuery.keywords" placeholder="关键字"></el-input>
      </el-form-item>
      <el-form-item prop="keywords">
        <el-select v-model="itemRequestQuery.status" placeholder="状态" style="width: 240px">
          <el-option label="全部" :value="-1"></el-option>
          <el-option label="未完成" :value="0"></el-option>
          <el-option label="已完成" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="getFoundItemPage">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Refresh" @click="queryFormRef?.resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
  <el-button :icon="Plus" type="primary" @click="dialogVisible = true" size="small"
  >新增
  </el-button>
  <el-table :data="itemRequestPage.list" style="width: 100%" v-loading="loading">
    <el-table-column prop="requestId" label="请求编号"/>
    <el-table-column prop="itemId" label="失物ID"/>
    <el-table-column prop="userId" label="发起人"/>
    <el-table-column prop="requestType" label="请求类型"/>
    <el-table-column prop="status" label="状态"/>
    <el-table-column prop="createdTime" label="创建时间"/>
    <el-table-column prop="contactInfo" label="联系方式"/>
    <el-table-column label="操作" width="250">
      <template #default="scope">
        <el-button type="primary" @click="openUpdate(scope.row.requestId)" size="small">修改</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button type="danger" @click="openDel(scope.row.requestId)" size="small">删除</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-dropdown>
          <el-button size="small">更多
            <el-icon class="el-icon--right">
              <arrow-down/>
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="openProcess(scope.row.requestId)">审核</el-dropdown-item>
              <el-dropdown-item>详情</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </el-table-column>
  </el-table>
  <div class="flex-end">
    <el-pagination
        v-model:current-page="itemRequestQuery.pageNum"
        v-model:page-size="itemRequestQuery.pageSize"
        :total="itemRequestPage.total"
        layout="prev, pager, next"
    >
    </el-pagination>
  </div>
  <el-dialog
      v-model="dialogVisible"
      :title="isAdd ? '新增':'修改'"
      width="600"
      @close="isAdd = true"
  >
    <el-form :model="itemRequestForm" label-width="120px" ref="itemRequestFromRef">
      <el-form-item label="证明材料（图片）">
        <el-upload
            v-model:file-list="fileList"
            action="/api/file/upload/serve/lost-found"
            list-type="picture-card"
            :on-success="handleUpload"
            :on-remove="handleRemove"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="失物ID">
        <el-input v-model="itemRequestForm.itemId"/>
      </el-form-item>
      <el-form-item label="发起人">
        <el-input v-model="itemRequestForm.userId"/>
      </el-form-item>
      <el-form-item label="丢失地点">
        <el-input v-model="itemRequestForm.lostLocation"/>
      </el-form-item>
      <el-form-item label="丢失时间">
        <el-date-picker v-model="itemRequestForm.lostTime" type="datetime" placeholder="选择日期时间"/>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input v-model="itemRequestForm.contactInfo"/>
      </el-form-item>
      <el-form-item label="认领状态">
        <el-radio-group v-model="itemRequestForm.status">
          <el-radio :value="0" size="large">待处理</el-radio>
          <el-radio :value="1" size="large">已验证</el-radio>
          <el-radio :value="2" size="large">已拒绝</el-radio>
          <el-radio :value="3" size="large">已完成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="物品描述">
        <el-input v-model="itemRequestForm.itemDescription" type="textarea"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFoundForm(itemRequestFromRef)">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
      v-model="processDialogVisible"
      title="审核"
      width="500"
  >
    <el-form :model="processForm">
      <el-form-item label="请求id">
        <el-input v-model="processForm.requestId" disabled/>
      </el-form-item>
      <el-form-item label="处理状态">
        <el-radio-group v-model="processForm.actionType">
          <el-radio :value="0">待处理</el-radio>
          <el-radio :value="1">已验证</el-radio>
          <el-radio :value="2">已拒绝</el-radio>
          <el-radio :value="3">已完成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="processForm.notes" type="textarea"/>
      </el-form-item>
      <el-form-item label="">
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcess">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, watch} from "vue";
import {Search, Refresh, Plus} from "@element-plus/icons-vue";
import {
  reqGetRequestProcessPage,
  reqAddItemRequest,
  reqUpdateItemRequest,
  reqDeleteItemRequest,
  reqGetItemRequestById, reqRequestProcess, reqGetRequestInfo
} from "@/api/serve/lost";
import type {FormInstance} from "element-plus";
import {ElMessage, ElMessageBox} from "element-plus";

let itemRequestQuery = reactive({
  keywords: "",
  status: -1,
  pageNum: 1,
  pageSize: 7
})
let fileList = ref([])
let itemRequestPage = reactive({
  total: 0,
  list: [],
  pageNum: 1,
})
let queryFormRef = ref<FormInstance>()
let itemRequestFromRef = ref<FormInstance>()
let loading = ref(true)
let isAdd = ref(true)
let dialogVisible = ref(false)
let processDialogVisible = ref(false)

let itemRequestForm = reactive({
  requestType: 0,//0丢失 1归还
  contactInfo: '',
  status: 0,
  userId: '',
  itemId: '',
  itemDescription: '',
  lostTime: Date,
  lostLocation: '',
  proofImages: [],
});
let processForm = reactive({
  requestId: null as number, //
  processorId: null, // 处理人id
  actionTime: Date,// 处理时间
  actionType: 0,//'verify' | 'reject' | 'complete'; // 处理状态
  notes: '', // 备注
  returnMethod: '', // 归还方式（线下，快递）
  completedTime: Date, // 归还完成时间
  rating: 0, // 评价
});
let openUpdate = (requestId: string) => {
  reqGetRequestInfo(requestId).then((res) => {
    Object.assign(itemRequestForm, res.data)
    itemRequestForm.proofImages=res.data.verifications.proofImages.split(',')
    //初始化显示的数组
    itemRequestForm.proofImages.forEach((item, index) => {
      fileList.value.push({
        name: item,
        url: item,
      })
    })
    dialogVisible.value = true
    isAdd.value = false
  })
}
let openProcess = (requestId: number) => {
  processForm.requestId = requestId
  processDialogVisible.value = true
}
let submitProcess = () => {
  reqRequestProcess(processForm).then((res) => {
    processDialogVisible.value = false
  })
}

let getFoundItemPage = () => {
  reqGetRequestProcessPage(itemRequestQuery).then((res) => {
    Object.assign(itemRequestPage, res.data)
    loading.value = false
  })
}
let handleUpload = (response, file, fileList) => {
  itemRequestForm.proofImages = fileList.map(item => item.response.data)
}
let handleRemove = (file, fileList) => {
  itemRequestForm.proofImages = fileList.map(item => item.response.data)
}
let submitFoundForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isAdd.value) {
        await reqAddItemRequest(itemRequestForm);
      } else {
        await reqUpdateItemRequest(itemRequestForm);
        isAdd.value = true;
      }
      await getFoundItemPage();
      dialogVisible.value = false;
    } else console.log("error submit!", fields);
  });
}
let openDel = (claimId: string) => {
  ElMessageBox.confirm("删除之后不能恢复，确认删除吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        reqDeleteItemRequest(claimId).then(() => {
          getFoundItemPage();
          ElMessage({
            message: "删除成功！",
            type: "success",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！",
        });
      });
};
onMounted(() => {
  getFoundItemPage()
})
watch([() => itemRequestQuery.pageNum, () => itemRequestQuery.pageSize], () => {
  getFoundItemPage()
})
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
